﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Jinndev.Localization {

    /// <summary>
    /// txt格式本地化文件加载器，每行一个键值对，以等号(=)分割，键值都不需要加引号<br/>
    /// 支持#和//开头的注释行
    /// </summary>
    public class TxtFileLocalizationLoader : ILocalizationLoader {

        public static readonly string FileNamePattern = "Localization_{0}.txt";

        public string Dir { get; private set; }

        public TxtFileLocalizationLoader(string dir) {
            Dir = dir;
        }

        public Dictionary<string, string> Load(SystemLanguage language) {
            string filePath = LocalizationUtil.FindClosestFile(language, Dir, FileNamePattern);
            if (filePath != null) {
                return LoadFile(filePath);
            }
            else {
                Debug.LogError($"Localization file not found for '{language}'");
            }
            return new Dictionary<string, string>();
        }

        public static Dictionary<string, string> LoadFile(string filePath) {
            Dictionary<string, string> dict = new Dictionary<string, string>();

            Stream stream = null;
            try {
                stream = ResourceManager.OpenRead(filePath);
                StreamReader reader = new StreamReader(stream, true);
                string line = null;
                while ((line = reader.ReadLine()) != null) {
                    if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#") || line.StartsWith("//")) {
                        continue;
                    }
                    string[] array = line.Split(new char[] { '=' }, 2, System.StringSplitOptions.RemoveEmptyEntries);
                    if (array.Length == 2) {
                        string key = array[0].Trim();
                        string text = array[1].Trim();

                        if (dict.ContainsKey(key)) {
                            Debug.LogError($"Text for '{key}' already exists");
                        }
                        else if (!string.IsNullOrWhiteSpace(key) || !string.IsNullOrWhiteSpace(text)) {
                            dict.Add(key, text);
                        }
                    }
                }
            }
            catch (System.Exception e) {
                Debug.LogException(e);
            }
            finally {
                stream?.Dispose();
            }
            return dict;
        }

    }

}
